package v3.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import v3.common.exception.ApiException;
import v3.common.object.QueryParamObject;
import v3.common.util.JwtUtil;
import v3.entity.User;
import v3.mapper.UserMapper;
import v3.service.UserService;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequiredArgsConstructor
@Service
public class UserServiceImpl  implements UserService {
    @Autowired
    private UserMapper userMapper;

    private final PasswordEncoder passwordEncoder;

    @Override
    public List<User> getList(QueryParamObject queryParamObject) {
        return  userMapper.getList(queryParamObject);
    }

    @Override
    public User detail(String userCode) {
        return  userMapper.detail(userCode);
    }

    @Override
    public User add(User user) {
        user.setUserPwd(passwordEncoder.encode(user.getUserPwd()));
        userMapper.add(user);
        return user;
    }

    @Override
    public User update(User user) {
        user.setUserPwd(passwordEncoder.encode(user.getUserPwd()));
        userMapper.update(user);
        return user;
    }
    public void delete(User user){
        userMapper.delete(user);
    }
    @Override
    public User login(User user){

       User userInfo = userMapper.findByUserCode(user);
       if(userInfo == null){
           throw new ApiException("用户不存在");
       }
       String pwd = user.getUserPwd();
       String pwd2 = userInfo.getUserPwd();
        if(passwordEncoder.matches(pwd,pwd2)){
            return userInfo;
        }else{
            throw new ApiException("账号或密码错误");
        }
    }
}
